package com.greenline.push.home.controllers.certificate;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.greenline.guser.annotation.GuserResource;
import com.greenline.push.common.json.BaseJson;
import com.greenline.push.common.json.GridJsonData;
import com.greenline.push.core.pushcenter.CertConfigManager;
import com.greenline.push.dal.pushcenter.dataobject.CertConfigDO;
import com.greenline.push.dal.query.CertConfigQuery;

@Controller
@RequestMapping(value = "/certificate")
public class CertificateController {

    @Resource
    private CertConfigManager certConfigManager;
    private final Log logger = LogFactory.getLog(CertificateController.class);

    private final String charset = "ISO-8859-1";

    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public String queryRecord(ModelMap model) {
        return "certificate/index";
    }

    @RequestMapping("/query.json")
    @ResponseBody
    public GridJsonData<CertConfigDO> listRecord(CertConfigQuery query,
            @RequestParam(value = "page", defaultValue = "1", required = false) String pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) String pageSize) {
        query.setPageIndex(Integer.parseInt(pageIndex));
        query.setPageSize(Integer.parseInt(pageSize));
        GridJsonData<CertConfigDO> ret = new GridJsonData<CertConfigDO>();
        ret.setQuery(certConfigManager.listByQuery(query));
        return ret;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addInit(ModelMap model) {
        return "certificate/add";
    }

    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson add(ModelMap model, @ModelAttribute("certificate") CertConfigDO certConfig) {
        BaseJson json = new BaseJson();
        try {
            if (certConfigManager.insert(certConfig) > 0) {
                json.setMessage("提交成功！");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String updateInit(ModelMap model, @PathVariable Long id) {
        CertConfigDO object = certConfigManager.getCertConfigById(id);
        model.put("certificate", object);
        return "certificate/update";
    }

    @RequestMapping(value = "/update/certificate/update.json", method = RequestMethod.POST)
    public @ResponseBody
    ModelAndView update(ModelMap model, @ModelAttribute("certificate") CertConfigDO certConfig, MultipartHttpServletRequest request
            ) {
        BaseJson json = new BaseJson();
        ModelAndView view = new ModelAndView("/certificate/update_result");
        if (StringUtils.isBlank(certConfig.getAppId())) {
            json.setHasError(true);
            json.setMessage("appId不可为空");
            view.addObject("issucc", false);
			view.addObject("result", "appId不可为空");
            return view;
        }
        String typeStr = "";
        try {
            typeStr = String.valueOf(certConfig.getType());
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("类型只能输入数字");
            view.addObject("issucc", false);
			view.addObject("result", "类型只能输入数字");
            return view;
        }
        if (StringUtils.isBlank(typeStr.trim())) {
            json.setHasError(true);
            json.setMessage("类型不可为空");
            view.addObject("issucc", false);
			view.addObject("result", "类型不可为空");
            return view;
        }
        if (StringUtils.isBlank(certConfig.getPassword())) {
            json.setHasError(true);
            json.setMessage("密码不可为空");
            view.addObject("issucc", false);
			view.addObject("result", "密码不可为空");
            return view;
        }
        String statusStr = "";
        try {
            statusStr = String.valueOf(certConfig.getStatus());
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("状态只能输入数字");
            view.addObject("issucc", false);
			view.addObject("result", "状态只能输入数字");
            return view;
        }
        if (StringUtils.isBlank(statusStr.trim())) {
            json.setHasError(true);
            json.setMessage("状态不可为空");
            view.addObject("issucc", false);
			view.addObject("result", "状态不可为空");
            return view;
        }
//        certConfig.setAppId(appId);
//        certConfig.setMemo(memo);
//        certConfig.setName(name);
//        certConfig.setPassword(pwd);
//        certConfig.setStatus(status);
//        certConfig.setType(type);
        MultipartFile file = request.getFile("file");
        InputStream in = null;
        try {
            in = file.getInputStream();

        } catch (IOException e) {
            e.printStackTrace();
            
        }

        String content = "";
        try {
            content = IOUtils.toString(in, charset);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            view.addObject("issucc", false);
			view.addObject("result", e.getMessage());
        }
        certConfig.setCertificate(content);
        try {
            if (certConfigManager.update(certConfig)) {
                json.setMessage("提交成功！");
                view.addObject("issucc", true);
    			view.addObject("result", "修改成功");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
                view.addObject("issucc", false);
    			view.addObject("result", "提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
            view.addObject("issucc", false);
			view.addObject("result", "提交出错");
        }
        return view;
    }

    @GuserResource("证书删除")
    @RequestMapping(value = "/delete.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson delete(ModelMap model, @ModelAttribute("id") Long id) {
        BaseJson json = new BaseJson();
        try {
            if (certConfigManager.delete(id)) {
                json.setMessage("删除成功！");
            } else {
                json.setHasError(true);
                json.setMessage("删除出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("删除出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView upload(MultipartHttpServletRequest request, String appId, String name, Integer type, String pwd, Integer status,
            String memo) {
        BaseJson json = new BaseJson();
        ModelAndView view = new ModelAndView("/certificate/upload_result");
        if (StringUtils.isBlank(appId)) {
            json.setHasError(true);
            json.setMessage("appId不可为空");
			view.addObject("issucc", false);
			view.addObject("result", "appId不可为空");
            return view;
        }
        String typeStr = "";
        try {
            typeStr = String.valueOf(type);
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("类型只能输入数字");
            view.addObject("issucc", false);
            view.addObject("result", "类型只能输入数字");
            return view;
        }
        if (StringUtils.isBlank(typeStr.trim())) {
            json.setHasError(true);
            json.setMessage("类型不可为空");
            view.addObject("issucc", false);
            view.addObject("result", "类型不可为空");
            return view;
        }
        if (StringUtils.isBlank(pwd)) {
            json.setHasError(true);
            json.setMessage("密码不可为空");
            view.addObject("issucc", false);
            view.addObject("result", "密码不可为空");
            return view;
        }
        String statusStr = "";
        try {
            statusStr = String.valueOf(status);
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("状态只能输入数字");
            view.addObject("issucc", false);
            view.addObject("result", "状态只能输入数字");
            return view;
        }
        if (StringUtils.isBlank(statusStr.trim())) {
            json.setHasError(true);
            json.setMessage("状态不可为空");
            view.addObject("issucc", false);
            view.addObject("result", "状态不可为空");
            return view;
        }
        CertConfigDO certConfig = new CertConfigDO();
        certConfig.setAppId(appId);
        certConfig.setMemo(memo);
        certConfig.setName(name);
        certConfig.setPassword(pwd);
        certConfig.setStatus(status);
        certConfig.setType(type);
        MultipartFile file = request.getFile("file");
        InputStream in = null;
        try {
            in = file.getInputStream();

        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }

        String content = "";
        try {
            content = IOUtils.toString(in, charset);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        certConfig.setCertificate(content);
        try {
            if (certConfigManager.insert(certConfig) > 0) {
                json.setMessage("提交成功！");
                view.addObject("issucc", true);
                view.addObject("result", "上传成功");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
                view.addObject("issucc", false);
                view.addObject("result", "提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            view.addObject("issucc", false);
            view.addObject("result", "提交出错");
            logger.error(json.getMessage(), e);
        }
        return view;
    }

}
